package com.lys.controller;

import com.lys.entity.Order;
import com.lys.entity.Product;
import com.lys.entity.User;
import com.lys.entity.UserAddress;
import com.lys.service.*;
import com.lys.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.soap.Addressing;
import java.util.List;

/**
 * @author 陆小根
 * @version 9.0.4
 * @Date 2022/5/30 8:03
 */
@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private ProductService productService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private ProductCategoryService productCategoryService;
    @Autowired
    private CartService cartService;
    @Autowired
    private UserAddressService userAddressService;

    /**
     * 添加到购物车
     *
     * @return
     */
    @GetMapping("/save")
    @ResponseBody
    public ReturnResult save(HttpSession session,
                            @RequestParam("entityId") String id,
                            @RequestParam("quantity") String quantityStr)  {
        // HttpSession session = request.getSession();
        ReturnResult result = new ReturnResult();
        //String id = request.getParameter("entityId");
        //String quantityStr = request.getParameter("quantity");
        Integer quantity = 1;
        if (!EmptyUtils.isEmpty(quantityStr))
            quantity = Integer.parseInt(quantityStr);
        //查询出商品
        Product product = productService.getProductById(Integer.valueOf(id));
        if(product.getStock()<quantity){
            return result.returnFail("商品数量不足");
        }
        //获取购物车
        ShoppingCart cart = null;
        try {
            cart = getCartFromSession(session);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //往购物车放置商品
        result=cart.addItem(product, quantity);
        if(result.getStatus()== Constants.ReturnResult.SUCCESS){
            cart.setSum((EmptyUtils.isEmpty(cart.getSum()) ? 0.0 : cart.getSum()) + (product.getPrice() * quantity * 1.0));
        }
        return result;
    }



    /**
     * 刷新购物车
     * @param session
     * @return
     */
    @GetMapping("/refresh")
    public String refreshCart(HttpSession session) {
        // HttpSession session = request.getSession();
        ShoppingCart cart = null;
        try {
            cart = getCartFromSession(session);
            cart = cartService.calculate(cart);
        } catch (Exception e) {
            e.printStackTrace();
        }

        session.setAttribute("cart", cart);//全部的商品
        return "/common/pre/searchBar";
    }

    /**
     * 跳到结算页面
     * @param model
     * @return
     */
    @GetMapping("/toSettlement")
    public String toSettlement(Model model) {
        List<ProductCategoryVo> productCategoryVoList = productCategoryService.queryAllProductCategoryList();
        //封装返回
        model.addAttribute("productCategoryVoList", productCategoryVoList);
        return "/pre/settlement/toSettlement";
    }

    /**
     * 跳转到购物车页面
     * @param session
     * @return
     */
    @GetMapping("/settlement1")
    public String settlement1(HttpSession session)  {
        ShoppingCart cart = null;
        try {
            cart = getCartFromSession(session);
            cart = cartService.calculate(cart);
        } catch (Exception e) {
            e.printStackTrace();
        }

        session.setAttribute("cart",cart);
        return "/pre/settlement/settlement1";
    }

    /**
     * 结算 形成预备订单
     * @return
     */
    @GetMapping("/settlement2")
    public String settlement2(HttpSession session,Model model)  {
        User user = getUserFromSession(session);
        List<UserAddress> userAddressList = null;
        try {
            userAddressList = userAddressService.queryUserAdressList(user.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("userAddressList", userAddressList);
        return "/pre/settlement/settlement2";
    }

    /**
     * 生成订单
     * @param request
     * @return
     */
    @GetMapping("/settlement3")
    public Object settlement3(HttpServletRequest request, HttpSession session)  {
        ShoppingCart cart = null;
        try {
            cart = getCartFromSession(session);
            cart = cartService.calculate(cart);
        } catch (Exception e) {
            e.printStackTrace();
        }

        User user = getUserFromSession(session);
        ReturnResult result= null;
        try {
            result = checkCart(session);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(result.getStatus()==Constants.ReturnResult.FAIL){
            return result;
        }
        //新增地址
        String addressId=request.getParameter("addressId");
        String newAddress=request.getParameter("newAddress");
        String newRemark=request.getParameter("newRemark");
        UserAddress userAddress=new UserAddress();
        if(addressId.equals("-1")){
            userAddress.setRemark(newRemark);
            userAddress.setAddress(newAddress);
            try {
                userAddress.setId(userAddressService.addUserAddress(user.getId(),newAddress,newRemark));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            userAddress=userAddressService.getUserAddressById(Integer.parseInt(addressId));
        }

        //生成订单
        Order order = orderService.payShoppingCart(cart,user,userAddress.getAddress());
        try {
            clearCart(session);
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setAttribute("currentOrder", order);
        return "/pre/settlement/settlement3";
    }

    /**
     * 清空购物车  没有按钮  是结账后清空
     */
    @GetMapping("/clear")
    @ResponseBody
    public ReturnResult clearCart(HttpSession session)  {
        ReturnResult result = new ReturnResult();
        //结账后清空购物车
        session.removeAttribute("cart");
        result.returnSuccess(null);
        return result;
    }

    /**
     * 修改购物车信息
     * @return
     */
    @GetMapping("/modify")
    @ResponseBody
    public ReturnResult modCart(HttpSession session,
                                @RequestParam("entityId") String id,
                                @RequestParam("quantity") String quantityStr)  {
        ReturnResult result = new ReturnResult();
        //HttpSession session = request.getSession();
        //String id = request.getParameter("entityId");
        //String quantityStr = request.getParameter("quantity");
        ShoppingCart cart = null;
        try {
            cart = getCartFromSession(session);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Product product=productService.getProductById(Integer.valueOf(id));
        if(EmptyUtils.isNotEmpty(quantityStr)){
            if(Integer.parseInt(quantityStr)>product.getStock()){
                return result.returnFail("商品数量不足");
            }
        }
        try {
            cart = cartService.modifyShoppingCart(id, quantityStr, cart);
        } catch (Exception e) {
            e.printStackTrace();
        }
        session.setAttribute("cart", cart);//全部的商品
        return result.returnSuccess();
    }


    /**
     * 从session中获取购物车
     * @param session
     * @return
     */
    private ShoppingCart getCartFromSession(HttpSession session) {
        ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
        if (cart == null) {
            cart = new ShoppingCart();
            session.setAttribute("cart", cart);
        }
        return cart;
    }

    private ReturnResult checkCart(HttpSession session)  {
        ReturnResult result = new ReturnResult();
        //HttpSession session = request.getSession();
        ShoppingCart cart = getCartFromSession(session);
        try {
            cart = cartService.calculate(cart);
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (ShoppingCartItem item : cart.getItems()) {
            Product product=productService.getProductById(item.getProduct().getId());
            if(product.getStock()<item.getQuantity()){
                return result.returnFail(product.getName()+"商品数量不足");
            }
        }
        return result.returnSuccess();
    }

    /**
     * @param session
     * @return
     */
    private User getUserFromSession(HttpSession session) {
        // HttpSession session = request.getSession();
        User user = (User) session.getAttribute("loginUser");
        return user;
    }
}
